// token鉴权文件
const { verify } = require('jsonwebtoken')

const { M_user } = require('../models/index')
const { secret } = require('./config')

const path = ['/users/login', '/users/register']

// token鉴权
const judge_token = async (ctx, next) => {
    if(ctx.response.status == 404) {
        ctx.body = {
            status: false,
            msg: ctx.response.message
        }
    }

    try {
        await next()
    } catch (error) {
        if (error == 'UnauthorizedError: Authentication Error') {
            ctx.body = {
                status: false,
                msg: '鉴权失败，请登录'
            }
        }
    }
}

// 容错中间件
const judge_login = async (ctx, next) => {
    let url = ctx.request.url
    if(path.includes(url)) { // 接口白名单
        await next()
    }else { // 判断是否登录 
        try {
            let token = ctx.header.authorization.replace('Bearer ', '')
            let _id = verify(token, secret)._id

            let result = await M_user.findOne({ _id })

            if(result) {
                await next()
            }else {
                ctx.body = {
                    status: false,
                    msg: '鉴权失败，请登录'
                }
            }
        } catch (error) {
            if (error == 'Error: Unexpected field') {
                ctx.body = {
                    status: false,
                    msg: '超过最大上传数量，最大上传数量为5'
                }
            } else if (error == "TypeError: Cannot read property 'mimetype' of undefined") {
                ctx.body = {
                    status: false,
                    msg: '图片格式不对，请重新上传'
                }
            } else {
                ctx.body = {
                    status: false,
                    msg: '鉴权失败，请登录'
                }
            }
            console.error('错误异常信息<<<<<<<<<', error);
        }
    }
}


module.exports = {
    judge_token,
    judge_login
}
